<script setup lang='tsx'>
import { ref, reactive,getCurrentInstance,nextTick, inject  } from "vue";
import WangEditor from "@/components/WangEditor/index.vue";
import { useRouter } from "vue-router";
import { useHandleData } from "@/hooks/useHandleData";
import { ElMessage, ElMessageBox } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import { ProTableInstance, ColumnProps, HeaderRenderScope } from "@/components/ProTable/interface";
import { CirclePlus, Delete, EditPen, Download, Upload, View, Refresh } from "@element-plus/icons-vue";

import {
 getEditorList,
getAddEditor,
getEditEditor,
getDelEditor
} from "@/api/modules/richText";


const content = ref("");

const dialogVisible = ref(false);

const preview = () => {
  dialogVisible.value = true;
};

const wangEditor=ref()

const editPreview=ref(false)

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({ type: 1 });

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，那么你可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
  return {
    list:data.list,
    total: data.total,
    pageNum: data.pageNum,
    pageSize: data.pageSize
  };
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
  return getEditorList(params);
};

// 自定义渲染表头（使用tsx语法）
const headerRender = (scope: HeaderRenderScope<any>) => {
  return (
    <el-button type="primary" onClick={() => ElMessage.success("我是通过 tsx 语法渲染的表头")}>
      {scope.column.label}
    </el-button>
  );
};

// 表格配置项
const columns: ColumnProps<any>[] = [
  { type: "selection", fixed: "left", width: 80 },
  { type: "index", label: "编号", width: 80 },
  {
    prop: "createTime",
    label: "创建时间",
    headerRender,
    
  },
   {
    prop: "updateTime",
    label: "更新时间",
    headerRender,
    
  },
  { prop: "operation", label: "操作", fixed: "right", width: 330 }
];

// 删除用户信息
const deleteAccount = async (params: any) => {
  await useHandleData(getDelEditor, { id: [params.id] }, `删除`);
  proTable.value?.getTableList();
};

// 批量删除用户信息
const batchDelete = async (id: string[]) => {
  await useHandleData(getDelEditor, { id }, "删除所选用户信息");
  proTable.value?.clearSelection();
  proTable.value?.getTableList();
};

const scrollTop:Function=inject('scrollTop') as Function

const id=ref()

const handleEdit = (row:any) => {
  id.value=row.id
  content.value=row.val 
  editPreview.value=true
  nextTick(()=>{
     scrollTop()
  })
};

/* const showEditor:Function=inject('showEditor') as Function */
const clear=()=>{
  content.value=''
  contentView.value=''
  id.value=''
  editPreview.value=false
  wangEditor.value.showEditor()
}

const contentView=ref()
const handlePreview=(row:any)=>{
  contentView.value=row.val
  dialogVisible.value=true
}

const handleAdd=async()=>{
  let result:any=await getAddEditor({val:content.value})
  if(result.code===200)  {ElMessage.success(result.msg);clear()}
  else  ElMessage.error('添加失败')
  proTable.value?.getTableList()
}

const comfirmEdit=async()=>{
  editPreview.value=false
  let result:any=await getEditEditor({val:content.value,id:id.value})
  if(result.code===200)  {ElMessage.success(result.msg);clear()}
  else  ElMessage.error('修改失败')
  proTable.value?.getTableList()
}

</script>

<template>
  <div>
    <div class="card content-box mb20">
      <span class="text">富文本编辑器</span>
      <WangEditor v-model:value="content" height="400px" ref="wangEditor" />
      <div class="buttons">
        <el-button type="primary" icon="plus" @click="handleAdd" :disabled="editPreview"> 新增内容 </el-button>
        <el-button type="primary" icon="view" @click="preview"> 预览内容 </el-button>
        <el-button type="primary" icon="edit" @click="comfirmEdit"> 修改内容 </el-button>
        <el-button type="primary" icon="close" @click="clear"> 清空内容 </el-button>
      </div>
      <el-dialog fullscreen v-model="dialogVisible" title="富文本内容预览" width="1300px" top="50px">
        <div class="view" v-html="contentView"></div>
      </el-dialog>
    </div>

    <div class="card mb20">
      <div class="table-box">
        <ProTable
          ref="proTable"
          title="用户列表"
          :columns="columns"
          :request-api="getTableList"
          :init-param="initParam"
          :data-callback="dataCallback"
        >
          <!-- 表格 header 按钮 -->
          <template #tableHeader="scope">
            <el-button
              type="danger"
              :icon="Delete"
              plain
              :disabled="!scope.isSelected"
              @click="batchDelete(scope.selectedListIds)"
            >
              批量删除用户
            </el-button>
          </template>
          <!-- Expand -->
          <template #expand="scope">
            {{ scope.row }}
          </template>
          <!-- createTime -->
          <template #createTime="scope">
            <el-button type="primary" link @click="ElMessage.success('我是通过作用域插槽渲染的内容')">
              {{ scope.row.createTime }}
            </el-button>
          </template>
          <!-- updateTime -->
          <template #updateTime="scope">
            <el-button type="primary" link @click="ElMessage.success('我是通过作用域插槽渲染的内容')">
              {{ scope.row.updateTime }}
            </el-button>
          </template>
          <!-- 表格操作 -->
          <template #operation="scope">
            <el-button type="primary" link :icon="View" @click="handlePreview(scope.row)"> 查看 </el-button>
            <el-button type="primary" link :icon="EditPen" @click="handleEdit(scope.row)"> 编辑 </el-button>
            <el-button type="primary" link :icon="Delete" @click="deleteAccount(scope.row)"> 删除 </el-button>
          </template>
        </ProTable>
      </div>
    </div>

    <div class="card">
      <el-descriptions title="配置项 📚" :column="1" border>
        <el-descriptions-item label="value"> 双向绑定的 value 值，使用示例： v-model:value="content"> </el-descriptions-item>
        <el-descriptions-item label="toolbarConfig">
          富文本 ToolBar区域 配置：
          <a href="https://www.wangeditor.com/v5/toolbar-config.html"> https://www.wangeditor.com/v5/toolbar-config.html </a>
        </el-descriptions-item>
        <el-descriptions-item label="editorConfig">
          富文本 编辑区域 配置：
          <a href="https://www.wangeditor.com/v5/editor-config.html"> https://www.wangeditor.com/v5/editor-config.html </a>
        </el-descriptions-item>
        <el-descriptions-item label="height"> 富文本高度，默认为 500px </el-descriptions-item>
        <el-descriptions-item label="mode"> 富文本模式，默认为 default（"default" | "simple"） </el-descriptions-item>
        <el-descriptions-item label="hideToolBar"> 隐藏 ToolBar 区域，默认为 false </el-descriptions-item>
        <el-descriptions-item label="disabled"> 禁用富文本编辑器，默认为 false </el-descriptions-item>
      </el-descriptions>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.el-button {
  margin-top: 20px;
}
:deep(.el-dialog__body) {
  height: 700px !important;
  overflow: auto;
}
.buttons {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
